package control;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import data.Constant;
import data.LoadData;
import data.TimeStock;

public class IndustryWeight {

	private Set<String> codeSet = null;
	private HashMap<String, BigDecimal> industryMap = new HashMap<String, BigDecimal>();
	private HashMap<String, List<TimeStock>> industryStocks = new HashMap<String, List<TimeStock>>();
	
	public IndustryWeight(Set<String> codeSet){
		this.codeSet = codeSet;
		dealWeight();
	}
	
	public HashMap<String, BigDecimal> getIndustryMap() {
		return industryMap;
	}
	
	private void insertStocks(Set<String> codeSet){
		for (String code : codeSet) {
			TimeStock ts = LoadData.getTimeStock(code);
			if(industryStocks.get(ts.getIndustry())==null){
				List<TimeStock> stocks = new ArrayList<TimeStock>();
				stocks.add(ts);
				industryStocks.put(ts.getIndustry(), stocks);
			}else{
				industryStocks.get(ts.getIndustry()).add(ts);
			}
		}
	}
	
	private void dealWeight(){
		insertStocks(codeSet);
		for (String industry : industryStocks.keySet()) {
			BigDecimal totalPercent = Constant.ZERO;
			List<TimeStock> stocks = industryStocks.get(industry);
			for (TimeStock ts : stocks) {
				totalPercent = totalPercent.add(ts.getRatePercent());
			}
			industryMap.put(industry, totalPercent.divide(new BigDecimal(stocks.size()),2,BigDecimal.ROUND_HALF_UP));
		}
	}
}
